package com.pengzy.auth.services;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pengzy.auth.dto.RegisterBo;
import com.pengzy.comment.core.generationID.SnowFlake;
import com.pengzy.comment.mybatis.entity.SysUser;
import com.pengzy.comment.mybatis.mapper.SysUserMapper;
import com.pengzy.comment.web.exception.CustomException;
import com.pengzy.comment.web.result.JsonResult;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author xiaozhi 2023/8/4
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    PasswordEncoder passwordEncoder;

    public static final SnowFlake SNK = new SnowFlake();

    @Override
    public JsonResult<Void> register(RegisterBo bo) {
        verifyBo(bo);
        SysUser user=new SysUser();
        user.setUserName(bo.getUser());
        user.setPassword(passwordEncoder.encode(bo.getFormPass()));
        user.setUserCode(String.valueOf(SNK.nextId()));
        sysUserMapper.insert(user);
        return JsonResult.success("注册成功");
    }

    public void verifyBo(RegisterBo bo){
        if(!bo.getPass().equals(bo.getFormPass())){
            throw new CustomException("密码不一致！");
        }
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper= Wrappers.lambdaQuery();
        sysUserLambdaQueryWrapper.eq(SysUser::getUserName,bo.getUser());
        sysUserLambdaQueryWrapper.last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(sysUserLambdaQueryWrapper);
        if(sysUser!=null){
            throw new CustomException("已存在此用户！");
        }
    }
}
